$(document).ready(function() {
    let currentPage = 1;
    const pageSize = 5;

    // 初始化加载数据
    loadUserRoleList();
    loadRoleOptions();

    // 加载用户角色列表
    function loadUserRoleList(params = {}) {
        let searchParams = {
            pageNum: currentPage,
            pageSize: pageSize
        };

        if (typeof params === 'string') {
            // 处理序列化的表单数据
            const formData = new URLSearchParams(params);
            if (formData.get('username')) searchParams.username = formData.get('username');
            if (formData.get('roleId')) searchParams.roleId = formData.get('roleId');
        } else {
            if (params.username) searchParams.username = params.username;
            if (params.roleId) searchParams.roleId = params.roleId;
            if (params.pageNum) searchParams.pageNum = params.pageNum;
        }

        $.ajax({
            url: contextPath + '/API/user/role',
            method: 'GET',
            data: searchParams,
            success: function(response) {
                if (response.code === 200) {
                    renderUserRoleTable(response.rows);
                    renderPagination(response.total);
                } else {
                    showResultModal('错误', response.msg);
                }
            },
            error: function() {
                showResultModal('错误', '加载数据失败');
            }
        });
    }

    // 渲染用户角色表格
    function renderUserRoleTable(data) {
        const tbody = $('#userRoleTable tbody');
        tbody.empty();

        data.forEach(function(item) {
            const roleNames = item.roles.map(role => role.role_name).join(', ');
            const tr = $('<tr>');
            tr.append(`
                <td class="text-center">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" value="${item.user_id}">
                    </div>
                </td>
                <td class="text-center">${item.username}</td>
                <td>${roleNames}</td>
                <td class="text-center">
                    <button class="btn btn-sm btn-primary edit-role" data-user-id="${item.user_id}" 
                            data-username="${item.username}" data-roles='${JSON.stringify(item.roles)}'>
                        <i class="bi bi-pencil"></i> 编辑
                    </button>
                </td>
            `);
            tbody.append(tr);
        });
    }

    // 渲染分页
    function renderPagination(total) {
        const totalPages = Math.ceil(total / pageSize);
        const pagination = $('#userRolePagination');
        pagination.empty();

        // 上一页
        pagination.append(`
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage - 1}">&laquo;</a>
            </li>
        `);

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            pagination.append(`
                <li class="page-item ${currentPage === i ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `);
        }

        // 下一页
        pagination.append(`
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage + 1}">&raquo;</a>
            </li>
        `);
    }

    // 加载角色选项
    function loadRoleOptions() {
        $.ajax({
            url: contextPath + '/API/role/list',
            method: 'GET',
            data: { pageSize: 100 }, // 获取所有角色
            success: function(response) {
                if (response.code === 200) {
                    const roles = response.rows;
                    // 更新搜索表单的角色下拉框
                    const roleSelect = $('select[name="roleId"]');
                    roleSelect.empty().append('<option value="">所有角色</option>');
                    roles.forEach(function(role) {
                        roleSelect.append(`<option value="${role.role_id}">${role.role_name}</option>`);
                    });

                    // 更新模态框的角色复选框
                    const roleCheckboxes = $('#roleCheckboxes, #editRoleCheckboxes');
                    roleCheckboxes.empty();
                    roles.forEach(function(role) {
                        roleCheckboxes.append(`
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" value="${role.role_id}" 
                                       id="role${role.role_id}" name="roles[]">
                                <label class="form-check-label" for="role${role.role_id}">
                                    ${role.role_name}
                                </label>
                            </div>
                        `);
                    });
                }
            }
        });
    }

    // 搜索表单提交
    $('#searchForm').on('submit', function(e) {
        e.preventDefault();
        currentPage = 1;
        loadUserRoleList($(this).serialize());
    });

    // 重置搜索
    $('#resetSearchBtn').on('click', function() {
        $('#searchForm')[0].reset();
        currentPage = 1;
        loadUserRoleList();
    });

    // 分页点击事件
    $('#userRolePagination').on('click', '.page-link', function(e) {
        e.preventDefault();
        const page = $(this).data('page');
        if (page && !$(this).parent().hasClass('disabled')) {
            currentPage = page;
            loadUserRoleList($('#searchForm').serialize());
        }
    });

    // 全选/取消全选
    $('#selectAllUsers').on('change', function() {
        const isChecked = $(this).prop('checked');
        $('#userRoleTable tbody .form-check-input').prop('checked', isChecked);
    });

    // 打开编辑角色模态框
    $('#userRoleTable').on('click', '.edit-role', function() {
        const userId = $(this).data('user-id');
        const username = $(this).data('username');
        const roles = $(this).data('roles');

        $('#editUserId').val(userId);
        $('#editUsername').val(username);

        // 重置所有复选框
        $('#editRoleCheckboxes input[type="checkbox"]').prop('checked', false);

        // 选中用户已有的角色
        roles.forEach(function(role) {
            $(`#editRoleCheckboxes input[value="${role.role_id}"]`).prop('checked', true);
        });

        $('#editUserRoleModal').modal('show');
    });

    // 保存编辑的角色
    $('#saveEditUserRoleBtn').on('click', function() {
        const userId = $('#editUserId').val();
        const roleIds = [];
        $('#editRoleCheckboxes input[type="checkbox"]:checked').each(function() {
            roleIds.push($(this).val());
        });

        $.ajax({
            url: contextPath + '/API/user/role',
            method: 'POST',
            data: {
                userId: userId,
                'roleIds[]': roleIds
            },
            success: function(response) {
                $('#editUserRoleModal').modal('hide');
                if (response.code === 200) {
                    showResultModal('成功', response.msg);
                    loadUserRoleList();
                } else {
                    showResultModal('错误', response.msg);
                }
            },
            error: function() {
                $('#editUserRoleModal').modal('hide');
                showResultModal('错误', '保存角色失败，请稍后重试');
            }
        });
    });

    // 显示结果提示框
    function showResultModal(title, message) {
        $('#resultModalTitle').text(title);
        $('#resultModalBody').text(message);
        $('#resultModal').modal('show');
    }
});